//
//  SwiftUIView.swift
//  
//
//  Created by sandsn on 2024/3/25.
//

import SwiftUI

public struct LSTextField: View {
    @Binding var isSecret: Bool
    @Binding var text: String
    var prompt: Text?
    @State private var showPrompt = false
    public init(text: Binding<String>, isSecret: Binding<Bool> = .constant(false), prompt: Text? = nil) {
        self._isSecret = isSecret
        self._text = text
        self.prompt = prompt
    }
    
    public var body: some View {
        if #available(iOS 15.0, *) {
            if isSecret {
                SecureField("", text: $text, prompt: prompt)
            } else {
                TextField("", text: $text, prompt: prompt)
            }
        } else {
            ZStack(alignment: .leading) {
                if showPrompt {
                    prompt
                        .foregroundColor(.gray)
                }
                if isSecret {
                    SecureField("", text: $text.onChange { value in
                        self.showPrompt = value.isEmpty
                    })
                } else {
                    TextField("", text: $text.onChange { value in
                        self.showPrompt = value.isEmpty
                    })
                }
            }
        }
    }
}

#Preview {
    LSTextField(text: .constant("text"), isSecret: .constant(false), prompt: Text("请输入密码"))
}
